<?php


namespace coco;


use coco\traits\Singleton;

class Log
{
    use Singleton;

    private $app;
    protected $loggers = [];
    protected $option;

    private function __construct(array $option = [])
    {
        $this->option = $option;
        $this->app = App::getInstance();
    }


    public function save()
    {
        $this->write(join("\r\n", $this->loggers), true);
        $this->loggers = [];
    }

    public function write(string $msg, bool $from_save = false)
    {
        if (empty($msg)) {
            return;
        }

        if (!$from_save) {
            $trace = debug_backtrace();
            $caller = $trace[1];
            if ($caller) {
                $msg .= ' at ' . $caller['class'] . $caller['type'] . $caller['function'];
            }

            $msg = date('[H:i:s] ') . $msg;
        }
        $runtime_path = $this->app->runtime_path;
        $log_path = $runtime_path . 'log/' . ($this->option['sub_path'] ?? '');
        if (!is_dir($log_path)) {
            if (false === mkdir($log_path, 0755, true)) {
                return;
            }
        }
        $log_name = date('y_m_d');
        file_put_contents($log_path . $log_name . '.log',
            $msg . "\r\n"
            , FILE_APPEND);
        if (is_file($log_path . $log_name . '.log') && 2 * 1024 * 1024 <= filesize($log_path . $log_name . '.log')) {
            //多进程改名忽略被其他进程改了
            @rename($log_path . $log_name . '.log', $log_path . $log_name . '_' . coco_microtime() . '.log');
        }
    }

    public function logger(string $msg)
    {
        if (empty($msg)) {
            return;
        }
        $trace = debug_backtrace();
        $caller = $trace[1];
        if ($caller) {
            $msg .= ' at ' . $caller['class'] . $caller['type'] . $caller['function'];
        }
        $this->loggers[] = date('[H:i:s] ') . $msg;
    }
}